package com.mtask.web.service.impl;


import com.mtask.common.dto.TaskProjectDTO;
import com.mtask.common.dto.vo.VersionVo;
import com.mtask.common.entity.task.TaskProject;
import com.mtask.web.repository.TaskProjectRepository;
import com.mtask.web.service.ProjectService;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ProjectServiceImpl implements ProjectService {
    @Resource
    private TaskProjectRepository taskProjectRepository;

    @Override
    public void save(TaskProject taskProject) {
        taskProjectRepository.save(taskProject);
    }

    @Override
    @Transactional
    public Page<TaskProject> findAll(Pageable pageable) {
//        Sort sort = Sort.by(Sort.Direction.DESC, "id");
//        PageRequest page = PageRequest.of(0, 20, sort);
        Page<TaskProject> all = taskProjectRepository.findAll(pageable);
        return all;
//        for (TaskProject taskProject : all.getContent()) {
//            Set<TaskGroup> realTaskGroup = (Set<TaskGroup>) Hibernate.unproxy(taskProject.getTaskGroups());
//            taskProject.setTaskGroups(realTaskGroup);
//        }
//
//        List<TaskProject> content = all.getContent().stream().map(taskProject -> {
//            TaskProject item = new TaskProject();
//            Set<TaskGroup> realTaskGroup = (Set<TaskGroup>) Hibernate.unproxy(taskProject.getTaskGroups());
//            item.setTaskGroups(realTaskGroup);
//            return item;
//        }).collect(Collectors.toList());
//
//
//        return new PageImpl<TaskProject>(content, all.getPageable(), all.getTotalElements());
////        return all;
    }

    @Override
    public List<VersionVo> getProjectVersion() {
        return new ArrayList<>();
    }

    @Override
    public void deleteById(Integer id) {
        taskProjectRepository.deleteById(id);
    }

    @Override
    public List<TaskProjectDTO> simpleAll() {
        List<TaskProject> taskProjects = taskProjectRepository.findAll();
        return taskProjects
                .stream()
                .map(
                        taskProject ->
                                TaskProjectDTO
                                        .builder()
                                        .projectName(taskProject.getName())
                                        .id(taskProject.getId())
                                        .build()
                )
                .collect(Collectors.toList());
    }
}
